cmake_minimum_required(VERSION 3.13)
project(hello_triangle)

set(CMAKE_CXX_STANDARD 17)

include_directories(${CMAKE_SOURCE_DIR}/src)
include_directories(${CMAKE_SOURCE_DIR}/src/graphicsEngineWebGPU)

if(EMSCRIPTEN)
    message("for web")
    SET(main_cpp "src/main-web.cpp")
    include_directories(${EMSCRIPTEN_SYSROOT}/include)
else ()
    message("for pc")
    find_package(glfw3 REQUIRED)
    SET(main_cpp "src/main.cpp")
    include_directories(/usr/local/include)
    set(DAWN_ROOT "dawn")
    include_directories(${DAWN_ROOT}/include)
    include_directories(${DAWN_ROOT}/out/Debug/gen/include)
endif()

# 创建可执行文件
add_executable(app
    src/graphicsEngineWebGPU/EngineWebGPU.cpp
    ${main_cpp}
)

if(EMSCRIPTEN)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0")  # 关闭优化
    set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g")  # 添加调试信息
    set(CMAKE_EXE_LINKER_FLAGS
        "${CMAKE_EXE_LINKER_FLAGS} -g -s WASM=1 --bind -s MODULARIZE=1 -s EXPORT_NAME=createModule -s EXPORTED_FUNCTIONS=_main,_init -s INITIAL_MEMORY=128MB -s USE_WEBGPU=1 -s ASYNCIFY=1")
else()
    # List all .a files
    file(GLOB DAWN_LIBS
        "${CMAKE_SOURCE_DIR}/dawn/out/Debug/src/dawn/common/*.a"
        "${CMAKE_SOURCE_DIR}/dawn/out/Debug/src/dawn/glfw/*.a"
        "${CMAKE_SOURCE_DIR}/dawn/out/Debug/src/dawn/native/*.a"
        "${CMAKE_SOURCE_DIR}/dawn/out/Debug/src/dawn/platform/*.a"
        "${CMAKE_SOURCE_DIR}/dawn/out/Debug/src/dawn/*.a"
        "${CMAKE_SOURCE_DIR}/dawn/out/Debug/src/tint/*.a"
        "${CMAKE_SOURCE_DIR}/dawn/out/Debug/third_party/abseil/absl/*/*.a"
    )

    # Create a custom command to combine libraries
    add_custom_command(
        OUTPUT ${CMAKE_SOURCE_DIR}/dawn/out/Debug/libdawn_combined.a
        COMMAND libtool -static -o ${CMAKE_SOURCE_DIR}/dawn/out/Debug/libdawn_combined.a ${DAWN_LIBS}
        DEPENDS ${DAWN_LIBS}
        COMMENT "Combining Dawn and Abseil static libraries into libdawn_combined.a"
    )

    # Add a custom target to ensure the command runs
    add_custom_target(combine_dawn_libs DEPENDS ${CMAKE_SOURCE_DIR}/dawn/out/Debug/libdawn_combined.a)

    add_dependencies(app combine_dawn_libs)


    # Link libraries
    target_link_libraries(app PRIVATE
        ${CMAKE_SOURCE_DIR}/dawn/out/Debug/libdawn_combined.a
        "-framework Metal"
        "-framework IOSurface"
        "-framework Foundation"
        "-framework QuartzCore"
        glfw
    )
endif()
